package cn.shop.crontab.task;

import cn.shop.transcation.order.entity.Order;
import cn.shop.transcation.order.mapper.OrderMapper;
import cn.shop.utils.enums.OrderStatus;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author : 李一涵
 * @date : Created in 2022-2-27 14:52
 * @description :
 */
@Service
@Slf4j
public class OrderPayTimeoutCheckTask {

	@Resource
	private OrderMapper mapper;

	private final static String SELECT = "select id, deal_time from `order` where status = 4 and deleted = false order by create_time asc";
	private final static String UPDATE = "update `order` set status = 2, update_time = ? where id = ?";

	@Scheduled(cron = "5 * * * * ?")
	@Transactional(rollbackFor = Exception.class)
	public void checkOrder() {

		List<Order> list = mapper.selectList(Wrappers.<Order>lambdaQuery().eq(Order::getStatus, OrderStatus.TRADING).orderByAsc(Order::getAuditTime));
		LocalDateTime now = LocalDateTime.now();
		for (Order order : list) {
			LocalDateTime fiveMinLater = order.getDealTime().plusMinutes(5);
			//log.info("订单待支付检查 订单号:{} 当前时间：{}，购买时间5分钟后：{}，是否在5分钟之前：{}", order.getId(), now, fiveMinLater, !now.isBefore(fiveMinLater));
			if (!now.isBefore(fiveMinLater)) {
				Order update = new Order();
				update.setId(order.getId());
				update.setStatus(OrderStatus.PASSED);
				int count = mapper.updateById(update);
			}
		}
	}
}
